package com.manager.commons;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.tools.zip.ZipEntry;

public class FileUtils {
	/**
	 * 把接受的全部文件打成压缩包 
	 * @param List<File>;  
	 * @param org.apache.tools.zip.ZipOutputStream  
	 */
	public static void zipFile
			(List files,org.apache.tools.zip.ZipOutputStream outputStream) {
		int size = files.size();
		for (int i = 0; i < size; i++) {
			File file = (File) files.get(i);
			zipFile(file, outputStream);
		}
	}
	
	/**  
	 * 根据输入的文件与输出流对文件进行打包
	 * @param File
	 * @param org.apache.tools.zip.ZipOutputStream
	 */
	public static void zipFile(File inputFile,
			org.apache.tools.zip.ZipOutputStream ouputStream) {
		try {
			if (inputFile.exists()) {
				if (inputFile.isFile()) {
					FileInputStream in = new FileInputStream(inputFile);
					BufferedInputStream bins = new BufferedInputStream(in , 512);
					ZipEntry entry = new ZipEntry(inputFile.getName());
					ouputStream.putNextEntry(entry);
					
					// 向压缩文件中输出数据   
					int nNumber;
					byte[] buffer = new byte[512];
					while ((nNumber = bins.read(buffer)) != -1) {
						ouputStream.write(buffer, 0, nNumber);
					}
					// 关闭创建的流对象   
					bins.close();
					in.close();
				} else {
					try {
						File[] files = inputFile.listFiles();
						for (int i = 0; i < files.length; i++) {
							zipFile(files[i], ouputStream);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	

	public static HttpServletResponse downloadZIP(List files,String serverPath,String showName, HttpServletResponse response) throws Exception
	{
		FileInputStream fileIn = null;
		File file = null;
		try
		{
			if(files == null || files.size()==0){
				return null;
			}
	        String tempName = RandomKey.generateID_Long_19().toString() + ".rar";
			String tempRar = serverPath + "temp\\" +tempName;
			file = new File(tempRar);
	        if (!file.exists()) {   
	            file.createNewFile();   
	        }

	    	//创建文件输出流
	        FileOutputStream fous = new FileOutputStream(file);   
	        /**打包的方法我们会用到ZipOutputStream这样一个输出流,
	         * 所以这里我们把输出流转换一下*/
	        org.apache.tools.zip.ZipOutputStream zipOut 
	        	= new org.apache.tools.zip.ZipOutputStream(fous);
	        /**这个方法接受的就是一个所要打包文件的集合，
	         * 还有一个ZipOutputStream*/
	        zipOut.setEncoding("UTF-8");
	        FileUtils.zipFile(files, zipOut);
	        zipOut.close();
	        fous.close();
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			fileIn = new FileInputStream(file);
			String fileName = "";
			if (!"".equals(showName) && null != showName)
			{
				fileName = new String(showName.getBytes("GBK"), "ISO8859_1");
			}
			else
			{
				fileName = new String(file.getName().getBytes("GBK"), "ISO8859_1");
			}
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			byte[] b = new byte[32768];
			int len;
			while ((len = fileIn.read(b)) > 0)
			{
				response.getOutputStream().write(b, 0, len);
			}
			response.getOutputStream().flush();
			response.getOutputStream().close();
		}
		catch(FileNotFoundException ex)
		{
			throw ex;
		}
		catch(IOException e)
		{
			throw e;
		}
		finally
		{
			try
			{
				if (fileIn != null)
				{
					fileIn.close();
				}
				if(file!=null){
					file.delete();
				}
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
		    

		}
		return response;
	}
	
}
